package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Sign;
import cn.wolfcode.trip.base.domain.UserSign;
import cn.wolfcode.trip.base.mapper.SignMapper;
import cn.wolfcode.trip.base.mapper.UserSignMapper;
import cn.wolfcode.trip.base.service.ISignService;
import cn.wolfcode.trip.base.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.SimpleFormatter;

@Service
public class SignServiceImpl implements ISignService {
    @Autowired
    private SignMapper signMapper;

    @Autowired
    private UserSignMapper userSignMapper;

    @Override
    public int insert(Sign record) {
        return 0;
    }

    @Override
    public Sign selectByPrimaryKey(Long id) {
        Sign sign = signMapper.selectByPrimaryKey(id);
        return sign;
    }

    @Override
    public List<Sign> selectAll() {

        return null;
    }

    @Override
    public Sign selectIntByUserId(Long userId) {

        return signMapper.selectIntByuserId(userId);
    }

    @Override
    public String updateByPrimaryKey(Sign record) {
        //查询每个用户的签到信息
        Sign sign = signMapper.selectIntAndDay(record.getUser_id());

        //判断该用户之前有没有签到过
        if (sign != null) {

            List<UserSign> signtimes = sign.getSigntimes();
            //判断是否签到过
            for (UserSign signtime : signtimes) {

                if (DateUtil.formatDate(signtime.getSigntime()).equals(DateUtil.formatDate(new Date()))) {

                    return "亲,您已经签到过了";
                }

            }


            //没签到过.积分加50,签到天数加1
            record.setIntegral(sign.getIntegral() + 50);

            //定义一个存放签到日期的天数
            int day = 0;
            int max = day;
            for (UserSign signtime : signtimes) {
                int date = signtime.getSigntime().getDate();
                if (date > max) {
                    max = date;
                }
            }


            if (new Date().getDate() - max > 1 && new Date().getDate() - max != 0) {
                record.setDays(0);
            } else {
                record.setDays(sign.getDays() + 1);
            }
            signMapper.updateByPrimaryKey(record);
        } else {
            Sign one = new Sign();
            one.setUser_id(record.getUser_id());
            one.setDays(0);
            one.setIntegral(50);
            signMapper.insert(one);
        }


        //设置签到过的时间
        UserSign userSign = new UserSign();
        userSign.setSigntime(new Date());
        userSign.setUser_id(record.getUser_id());
        userSignMapper.insert(userSign);
        return "";
    }
}
